﻿//====================================================================================================
// [插件名称] jQuery formValidator
//----------------------------------------------------------------------------------------------------
// [描    述] jQuery formValidator表单验证插件，它是基于jQuery类库，实现了js脚本于页面的分离。对一个表
//            单对象，你只需要写一行代码就可以轻松实现20种以上的脚本控制。现支持一个表单元素累加很多种
//            校验方式,采用配置信息的思想，而不是把信息写在表单元素上，能比较完美的实现ajax请求。
//----------------------------------------------------------------------------------------------------
// [作者网名] 猫冬
// [邮    箱] wzmaodong@126.com
// [作者博客] http://wzmaodong.cnblogs.com
// [QQ群交流] 74106519
// [更新日期] 2011-05-22
// [版 本 号] ver4.0.1
//====================================================================================================
(function($){$.formValidator={initConfig:function(a){var b={debug:!1,validatorGroup:"1",alertMessage:!1,validObjects:[],ajaxObjects:"",forceValid:!1,onSuccess:function(){return!0},onError:$.noop,submitOnce:!1,formID:"",submitButtonID:"",autoTip:!1,tidyMode:!1,errorFocus:!0,wideWord:!0,status:"",submitAfterAjaxPrompt:"当前有数据正在进行服务器端校验，请稍候",validCount:0,ajaxCountSubmit:0,ajaxCountValid:0,inIframe:!1};a=a||{},$.extend(b,a),b.tidyMode&&(b.errorFocus=!1),b.formID!=""?$("#"+b.formID).submit(function(){return $.formValidator.bindSubmit(b)}):b.submitButtonID!=""&&$("#"+b.submitButtonID).click(function(){return $.formValidator.bindSubmit(b)}),$("body").data(b.validatorGroup,b)},bindSubmit:function(a){if(a.ajaxCountValid>0&&a.submitAfterAjaxPrompt!=""){alert(a.submitAfterAjaxPrompt);return!1}return $.formValidator.pageIsValid(a.validatorGroup)},sustainType:function(a,b){var c=$("#"+a).get(0),d=c.tagName,e=c.type;switch(b.validateType){case"InitValidator":return!0;case"InputValidator":return d=="INPUT"||d=="TEXTAREA"||d=="SELECT";case"CompareValidator":return d=="INPUT"||d=="TEXTAREA"?e!="checkbox"&&e!="radio":!1;case"AjaxValidator":return e=="text"||e=="textarea"||e=="file"||e=="password"||e=="select-one";case"RegexValidator":return d=="INPUT"||d=="TEXTAREA"?e!="checkbox"&&e!="radio":!1;case"FunctionValidator":return!0}},appendValid:function(a,b){if(!$.formValidator.sustainType(a,b))return-1;var c=$("#"+a).get(0);if(b.validateType=="InitValidator"||c.settings==undefined)c.settings=[];var d=c.settings.push(b);c.settings[d-1].index=d-1;return d-1},setTipState:function(a,b,c){var d=$("body").data(a.validatorGroup),e=$("#"+a.settings[0].tipID);c==null||c==""?e.hide():d.tidyMode?($("#fv_content").html(c),a.Tooltip=c,b!="onError"&&e.hide()):e.show().removeClass().addClass(b).html(c)},resetTipState:function(a){a==undefined&&(a="1");var b=$("body").data(a);$.each(b.validObjects,function(){var a=this.get(0),b=a.settings[0],c=b.defaultPassed;$.formValidator.setTipState(a,c?"onCorrect":"onShow",c?b.onCorrect:b.onShow)})},setFailState:function(a,b){var c=$("#"+a);c.removeClass().addClass("onError").html(b)},showMessage:function(a){var b=a.id,c=$("#"+b).get(0),d=a.isValid,e=a.setting,f="",g="",h=$("body").data(c.validatorGroup);d?(f=$.formValidator.isEmpty(b)?e.onEmpty:e.onCorrect,$.formValidator.setTipState(c,"onCorrect",f)):(g="onError",e.validateType=="AjaxValidator"?e.lastValid==""?(g="onLoad",f=e.onWait):f=e.onError:f=a.errormsg==""?e.onError:a.errormsg,h.alertMessage?c.validValueOld!=$(c).val()&&alert(f):$.formValidator.setTipState(c,g,f));return f},showAjaxMessage:function(a){var b=$("#"+a.id).get(0),c=b.settings[a.ajax],d=b.validValueOld,e=$(b).val();a.setting=c,d!=e||d==e&&!b.onceValided?$.formValidator.ajaxValid(a):(c.isValid!=undefined&&!c.isValid&&(b.lastshowclass="onError",b.lastshowmsg=c.onError),$.formValidator.setTipState(b,b.lastshowclass,b.lastshowmsg))},getLength:function(a){var b=$("#"+a),c=b.get(0),d=c.type,e=0;switch(d){case"text":case"hidden":case"password":case"textarea":case"file":var f=b.val(),g=$("body").data(c.validatorGroup);if(g.wideWord)for(var h=0;h<f.length;h++)e=e+(f.charCodeAt(h)>=19968&&f.charCodeAt(h)<=40869?2:1);else e=f.length;break;case"checkbox":case"radio":e=$("input[type='"+d+"'][name='"+b.attr("name")+"']:checked").length;break;case"select-one":e=c.options?c.options.selectedIndex:-1;break;case"select-multiple":e=$("select[name="+c.name+"] option:selected").length}return e},isEmpty:function(a){return $("#"+a).get(0).settings[0].empty&&$.formValidator.getLength(a)==0},isOneValid:function(a){return $.formValidator.oneIsValid(a).isValid},oneIsValid:function(a){var b=new Object,c=$("#"+a).get(0);b.initConfig=$("body").data(c.validatorGroup),b.id=a,b.ajax=-1,b.errormsg="";var d=c.settings,e=d.length,f;e==1&&(d[0].bind=!1);if(!d[0].bind)return null;for(var g=0;g<e;g++){if(g==0){if($.formValidator.isEmpty(a)){b.isValid=!0,b.setting=d[0];break}continue}b.setting=d[g],f=d[g].validateType;switch(f){case"InputValidator":$.formValidator.inputValid(b);break;case"CompareValidator":$.formValidator.compareValid(b);break;case"RegexValidator":$.formValidator.regexValid(b);break;case"FunctionValidator":$.formValidator.functionValid(b);break;case"AjaxValidator":b.ajax=g}c.onceValided=!0;if(!d[g].isValid){b.isValid=!1,b.setting=d[g];break}b.isValid=!0,b.setting=d[0];if(d[g].validateType=="AjaxValidator")break}return b},pageIsValid:function(a){a==undefined&&(a="1");var b=!0,c,d="",e,f="^",g,h,i="^",j=[],k=$("body").data(a);k.status="sumbiting",k.ajaxCountSubmit=0,$.each(k.validObjects,function(){this.settings[0].bind&&this.validatorAjaxIndex!=undefined&&this.onceValided==undefined&&(c=$.formValidator.oneIsValid(this.id),c.ajax==this.validatorAjaxIndex&&(k.status="sumbitingWithAjax",$.formValidator.ajaxValid(c)))});if(k.ajaxCountSubmit>0)return!1;$.each(k.validObjects,function(){if(this.settings[0].bind){h=this.name;if(i.indexOf("^"+h+"^")==-1){onceValided=this.onceValided==undefined?!1:this.onceValided,h&&(i=i+h+"^"),c=$.formValidator.oneIsValid(this.id);if(c){c.isValid||(b=!1,e=c.errormsg==""?c.setting.onError:c.errormsg,j[j.length]=e,g==null&&(g=c.id),d==""&&(d=e));if(!k.alertMessage){var a=this.settings[0].tipID;f.indexOf("^"+a+"^")==-1&&(c.isValid||(f=f+a+"^"),$.formValidator.showMessage(c))}}}}}),b?(k.onSuccess(),k.submitOnce&&$(":submit,:button,:reset").attr("disabled",!0)):(k.onError(d,$("#"+g).get(0),j),g&&k.errorFocus&&$("#"+g).focus()),k.status="init";return !k.debug&&b},ajaxValid:function(a){var b=a.id,c=$("#"+b),d=c.get(0),e=a.initConfig,f=d.settings,g=f[a.ajax],h=g.url,i=d.validatorGroup,e=$("body").data(i),j=$(e.ajaxObjects).serialize();j="clientid="+b+"&"+(g.randNumberName?g.randNumberName+"="+((new Date).getTime()+Math.round(Math.random()*1e4)):"")+(j.length>0?"&"+j:""),h=h+(h.indexOf("?")>-1?"&"+j:"?"+j),$.ajax({type:g.type,url:h,cache:g.cache,data:g.data,async:g.async,timeout:g.timeout,dataType:g.dataType,success:function(b,c,h){var j,k,l;$.formValidator.dealAjaxRequestCount(i,-1),j=g.success(b,c,h),g.isValid=j,j?(k="onCorrect",l=f[0].onCorrect):(k="onError",l=g.onError),$.formValidator.setTipState(d,k,l),a.initConfig.status=="sumbitingWithAjax"&&a.initConfig.ajaxCountSubmit==0&&(e.formID!=""?$("#"+e.formID).trigger("submit"):e.formID!=""&&$("#"+e.submitButtonID).trigger("click"))},complete:function(a,b){g.buttons&&g.buttons.length>0&&g.buttons.attr({disabled:!1}),g.complete(a,b)},beforeSend:function(b,c){this.lastXMLHttpRequest&&this.lastXMLHttpRequest.abort(),this.lastXMLHttpRequest=b,g.buttons&&g.buttons.length>0&&g.buttons.attr({disabled:!0});var e=g.beforeSend(b,c);e&&(g.isValid=!1,$.formValidator.setTipState(d,"onLoad",f[a.ajax].onWait)),g.lastValid="-1",e&&$.formValidator.dealAjaxRequestCount(i,1);return e},error:function(a,b,c){$.formValidator.dealAjaxRequestCount(i,-1),$.formValidator.setTipState(d,"onError",g.onError),g.isValid=!1,g.error(a,b,c)},processData:g.processData})},dealAjaxRequestCount:function(a,b){var c=$("body").data(a);c.ajaxCountValid=c.ajaxCountValid+b,c.status=="sumbitingWithAjax"&&(c.ajaxCountSubmit=c.ajaxCountSubmit+b)},regexValid:function(returnObj){var id=returnObj.id,setting=returnObj.setting,srcTag=$("#"+id).get(0).tagName,elem=$("#"+id).get(0),isValid;if(elem.settings[0].empty&&elem.value=="")setting.isValid=!0;else{var regexArray=setting.regExp;setting.isValid=!1,typeof regexArray=="string"&&(regexArray=[regexArray]),$.each(regexArray,function(){var r=this;setting.dataType=="enum"&&(r=eval("regexEnum."+r));if(r==undefined||r=="")return!1;isValid=(new RegExp(r,setting.param)).test($(elem).val());if(setting.compareType=="||"&&isValid){setting.isValid=!0;return!1}if(setting.compareType=="&&"&&!isValid)return!1}),setting.isValid||(setting.isValid=isValid)}},functionValid:function(a){var b=a.id,c=a.setting,d=$("#"+b),e=c.fun(d.val(),d.get(0));e!=undefined&&(typeof e=="string"?(c.isValid=!1,a.errormsg=e):c.isValid=e)},inputValid:function(a){var b=a.id,c=a.setting,d=$("#"+b),e=d.get(0),f=d.val(),g=e.type,h=$.formValidator.getLength(b),i=c.empty,j=!1;switch(g){case"text":case"hidden":case"password":case"textarea":case"file":c.type=="size"&&(i=c.empty,i.leftEmpty||(j=f.replace(/^[ \s]+/,"").length!=f.length),!j&&!i.rightEmpty&&(j=f.replace(/[ \s]+$/,"").length!=f.length),j&&i.emptyError&&(a.errormsg=i.emptyError));case"checkbox":case"select-one":case"select-multiple":case"radio":var k=!1;if(g=="select-one"||g=="select-multiple")c.type="size";var l=c.type;if(l=="size")j||(k=!0),k&&(f=h);else if(l=="date"||l=="datetime"){var m=!1;l=="date"&&(k=isDate(f)),l=="datetime"&&(k=isDate(f)),k&&(f=new Date(f),c.min=new Date(c.min),c.max=new Date(c.max))}else stype=typeof c.min,stype=="number"&&(f=(new Number(f)).valueOf(),isNaN(f)||(k=!0)),stype=="string"&&(k=!0);c.isValid=!1,k&&(f<c.min||f>c.max?(f<c.min&&c.onErrorMin&&(a.errormsg=c.onErrorMin),f>c.min&&c.onErrorMax&&(a.errormsg=c.onErrorMax)):c.isValid=!0)}},compareValid:function(a){var b=a.id,c=a.setting,d=$("#"+b),e=$("#"+c.desID),f=c.dataType;curvalue=d.val(),ls_data=e.val();if(f=="number")if(!isNaN(curvalue)&&!isNaN(ls_data))curvalue=parseFloat(curvalue),ls_data=parseFloat(ls_data);else return;if(f=="date"||f=="datetime"){var g=!1;f=="date"&&(g=isDate(curvalue)&&isDate(ls_data)),f=="datetime"&&(g=isDateTime(curvalue)&&isDateTime(ls_data));if(g)curvalue=new Date(curvalue),ls_data=new Date(ls_data);else return}switch(c.operateor){case"=":c.isValid=curvalue==ls_data;break;case"!=":c.isValid=curvalue!=ls_data;break;case">":c.isValid=curvalue>ls_data;break;case">=":c.isValid=curvalue>=ls_data;break;case"<":c.isValid=curvalue<ls_data;break;case"<=":c.isValid=curvalue<=ls_data;break;default:c.isValid=!1}},localTooltip:function(a){a=a||window.event;var b=a.pageX||(a.clientX?a.clientX+document.body.scrollLeft:0),c=a.pageY||(a.clientY?a.clientY+document.body.scrollTop:0);$("#fvtt").css({top:c+2+"px",left:b-40+"px"})},reloadAutoTip:function(a){a==undefined&&(a="1");var b=$("body").data(a);$.each(b.validObjects,function(){if(b.autoTip&&!b.tidyMode){var a=this.settings[0],c="#"+a.relativeID,d=$(c).offset(),e=d.top,f=$(c).width()+d.left;$("#"+a.tipID).parent().show().css({left:f+"px",top:e+"px"})}})}},$.fn.formValidator=function(a){var b={validatorGroup:"1",empty:!1,autoModify:!1,onShow:"请输入内容",onFocus:"请输入内容",onCorrect:"输入正确",onEmpty:"输入内容为空",defaultValue:null,bind:!0,ajax:!1,validateType:"InitValidator",tipCss:{left:"10px",top:"1px",height:"20px",width:"250px"},triggerEvent:"blur",forceValid:!1,tipID:null,relativeID:null,index:0};a=a||{},a.validatorGroup==undefined&&(a.validatorGroup="1");var c=$("body").data(a.validatorGroup);c.validCount+=1,c.tidyMode&&(b.tipCss={left:"2px",width:"22px",height:"22px",display:"none"}),c.alertMessage&&(b.autoModify=!0),$.extend(!0,b,a);return this.each(function(d){this.validatorIndex=c.validCount-1,this.validatorGroup=a.validatorGroup;var e=$(this),f={};$.extend(!0,f,b);var g=f.tipID?f.tipID:this.id+"Tip";if(c.autoTip)if(!c.tidyMode){if($("body [id="+g+"]").length==0){var h=f.relativeID?f.relativeID:this.id,i=$("#"+h).position(),j=i.top,k=$("#"+h).width()+i.left,l=$("<div class='formValidateTip'></div>");c.inIframe&&l.hide(),l.appendTo($("body")).css({left:k+"px",top:j+"px"}).prepend($('<div id="'+g+'"></div>').css(f.tipCss)),b.relativeID=h}}else e.showTooltips();b.tipID=g,$.formValidator.appendValid(this.id,b);if($.inArray(e,c.validObjects)==-1){if(f.ajax){var m=c.ajaxObjects;c.ajaxObjects=m+(m!=""?",#":"#")+this.id}c.validObjects.push(this)}c.alertMessage||$.formValidator.setTipState(this,"onShow",b.onShow);var n=this.tagName.toLowerCase(),o=this.type,p=b.defaultValue;p&&e.val(p),n=="input"||n=="textarea"?(e.focus(function(){if(!c.alertMessage){var a=$("#"+g);this.lastshowclass=a.attr("class"),this.lastshowmsg=a.html(),$.formValidator.setTipState(this,"onFocus",b.onFocus)}if(o=="password"||o=="text"||o=="textarea"||o=="file")this.validValueOld=e.val()}),e.bind(b.triggerEvent,function(){var a=this.settings,d=$.formValidator.oneIsValid(this.id);if(d!=null)if(d.ajax>=0)$.formValidator.showAjaxMessage(d);else{var e=$.formValidator.showMessage(d);if(!d.isValid){var f=b.autoModify&&(this.type=="text"||this.type=="textarea"||this.type=="file");if(f)$(this).val(this.validValueOld),c.alertMessage||$.formValidator.setTipState(this,"onShow",b.onShow);else if(c.forceValid||b.forceValid)alert(e),this.focus()}}})):n=="select"&&e.bind({focus:function(){c.alertMessage||$.formValidator.setTipState(this,"onFocus",b.onFocus)},blur:function(){$(this).trigger("change")},change:function(){var a=$.formValidator.oneIsValid(this.id);a!=null&&(a.ajax>=0?$.formValidator.showAjaxMessage(a):$.formValidator.showMessage(a))}})})},$.fn.inputValidator=function(a){var b={isValid:!1,min:0,max:99999999999999,type:"size",onError:"输入错误",validateType:"InputValidator",empty:{leftEmpty:!0,rightEmpty:!0,leftEmptyError:null,rightEmptyError:null}};a=a||{},$.extend(!0,b,a);return this.each(function(){$.formValidator.appendValid(this.id,b)})},$.fn.compareValidator=function(a){var b={isValid:!1,desID:"",operateor:"=",onError:"输入错误",validateType:"CompareValidator"};a=a||{},$.extend(!0,b,a);return this.each(function(){$.formValidator.appendValid(this.id,b)})},$.fn.regexValidator=function(a){var b={isValid:!1,regExp:"",param:"i",dataType:"string",compareType:"||",onError:"输入的格式不正确",validateType:"RegexValidator"};a=a||{},$.extend(!0,b,a);return this.each(function(){$.formValidator.appendValid(this.id,b)})},$.fn.functionValidator=function(a){var b={isValid:!0,fun:function(){this.isValid=!0},validateType:"FunctionValidator",onError:"输入错误"};a=a||{},$.extend(!0,b,a);return this.each(function(){$.formValidator.appendValid(this.id,b)})},$.fn.ajaxValidator=function(a){var b={type:"GET",url:"",dataType:"html",timeout:1e5,data:null,async:!0,cache:!1,beforeSend:function(){return!0},success:function(){return!0},complete:function(){},processData:!0,error:function(){},isValid:!1,lastValid:"",buttons:null,oneceValid:!1,randNumberName:"rand",onError:"服务器校验没有通过",onWait:"正在等待服务器返回数据",ajaxExistsError:"前面的校验尚未完成，请稍候...",validateType:"AjaxValidator"};a=a||{},$.extend(!0,b,a);return this.each(function(){var a=$("body").data(this.validatorGroup),c=a.ajaxObjects;(c+",").indexOf("#"+this.id+",")==-1&&(a.ajaxObjects=c+(c!=""?",#":"#")+this.id),this.validatorAjaxIndex=$.formValidator.appendValid(this.id,b)})},$.fn.defaultPassed=function(a){return this.each(function(){var b=this.settings;b[0].defaultPassed=!0;for(var c=1;c<b.length;c++){b[c].isValid=!0;if(!$("body").data(b[0].validatorGroup).alertMessage){var d=a?"onShow":"onCorrect";$.formValidator.setTipState(this,d,b[0].onCorrect)}}})},$.fn.unFormValidator=function(a){return this.each(function(){this.settings[0].bind=!a,a?$("#"+this.settings[0].tipID).hide():$("#"+this.settings[0].tipID).show()})},$.fn.showTooltips=function(){$("body [id=fvtt]").length==0&&(fvtt=$("<div id='fvtt' style='position:absolute;z-index:56002'></div>"),$("body").append(fvtt),fvtt.before("<iframe src='about:blank' class='fv_iframe' scrolling='no' frameborder='0'></iframe>"));return this.each(function(){jqobj=$(this),s=$("<span class='top' id=fv_content style='display:block'></span>"),b=$("<b class='bottom' style='display:block' />"),this.tooltip=$("<span class='fv_tooltip' style='display:block'></span>").append(s).append(b).css({filter:"alpha(opacity:95)",KHTMLOpacity:"0.95",MozOpacity:"0.95",opacity:"0.95"}),jqobj.bind({mouseover:function(a){$("#fvtt").append(this.tooltip),$("#fv_content").html(this.Tooltip),$.formValidator.localTooltip(a)},mouseout:function(){$("#fvtt").empty()},mousemove:function(a){$("#fv_content").html(this.Tooltip),$.formValidator.localTooltip(a)}})})}})(jQuery)